const db = require("../models");
const logger = require("../utils/utils.logger").logger();
const { aes } = require("../utils/utils.crypto");
const Users = db.users;
const UserInfo = db.userInfo;
const jwt = require("jsonwebtoken");

exports.login = function (pm, cb) {
  //登录逻辑
  Users.findOne({ where: { userphone: pm.userphone } })
    .then(async (data) => {
      logger.debug(
        "login => userphone:%s,password:%s",
        pm.userphone,
        aes.en(pm.password)
      );
      if (aes.en(pm.password) === data.password) {
        // 生成token
        let token =
          "Bearer " +
          jwt.sign(
            {
              userphone: pm.userphone,
              password: pm.password,
            },
            process.env["SIGN_KEY"],
            {
              expiresIn: 3600 * 24 * 3,
            }
          );
        const userInfoDetail = await UserInfo.findOne({
          where: { uid: data.uid },
        });
        console.log(userInfoDetail);

        let userInfo = {
          userInfoDetail,
          token,
          uid: data.uid,
          userPhone: data.userphone,
        };
        cb(userInfo);
        return;
      }
      cb(null, "密码错误！");
    })
    .catch((err) => {
      logger.error(JSON.stringify(err));
      cb(null, "用户不存在！请先注册");
    });
};
